﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using Business;
using Domain.Entities;
using MAF.Common;
using MAF.CRUD;
using Web.Controller;
using System.Reflection;

namespace Web.UI
{
    public class ArticleUI
    {
        /// <summary>
        /// 固定模块的Li列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        public static string FixedLi(Guid parentId, string module)
        {
            BaseQueryVo vo = new BaseQueryVo();
            vo.ParentId = parentId.ToString();
            
            ICRUD<Content> op = BusinessFactory.CreateArticle(module);
            return GetList(op.Index(vo),module);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="n">要查找的记录数</param>
        /// <param name="module"></param>
        /// <returns></returns>
        public static string FixedLi(int n, string module)
        {
            BaseQueryVo vo = new BaseQueryVo();
            vo.Page = new PageInfo(n, 1);

            ICRUD<Content> op = BusinessFactory.CreateArticle(module);
            return GetList(op.Index(vo), module);
        }

        private static string GetList(IList<Content> list,string module)
        {
            List<string> ss = new List<string>();
            foreach (Content info in list)
            {
                ss.Add(string.Format("<li><a href='Default.aspx?Module={0}&Handler=Article&Action=Show&Id={1}' class='txt'>{2}</a><em class='time'>{3}</em></li>"
                                        , module
                                        , info.Id
                                        , info.Name
                                        , info.PublishedDate.ToString("yyyy-MM-dd")));
            }
            return string.Join("\n", ss.ToArray());
        }
    }

    public class CategoryUI
    {
        public static string Options(Guid id)
        {
            CategoryHandler h = new CategoryHandler();
            IList<CategoryInfo> list = h.Index();

            List<string> ss = new List<string>();
            foreach (CategoryInfo info in list)
            {
                string selected = (info.Id == id) ? "selected='selected'" : "";
                ss.Add(string.Format(@"<option value='{0}' {2}>{1}</option>"
                                        , info.Id
                                        , info.Name
                                        , selected));
            }
            return string.Join("\n", ss.ToArray());
        }

        public static string Options()
        {
            return Options(Guid.Empty);
        }
    }

    public class DealerUI
    {
        DealerHandler _h = new DealerHandler();

        /// <summary>
        /// 验证供应商
        /// </summary>
        /// <returns></returns>
        public string Valid()
        {
            NameValueCollection nvc = new NameValueCollection(HttpContext.Current.Request.Form);
            if (string.IsNullOrEmpty(nvc["Name"])
                && string.IsNullOrEmpty(nvc["Url"])
                && string.IsNullOrEmpty(nvc["Code"]))
            {
                return "至少要输入一个条件";
            }

            try
            {
                IList<DealerInfo> list = _h.Index();
                if (0 == list.Count)
                    return "没有找到供应商";

                StringBuilder sb = new StringBuilder("<div>");
                foreach (DealerInfo info in list)
                {
                    sb.AppendFormat(@"
<p>经销商名称：{0}</p>
<p>经销商网址：{1}</p>
<p>经销商编码：{2}</p>
<p>为官方授权经销商</p>", info.Name, info.Url, info.Code);
                }
                sb.Append("</div>");
                return sb.ToString();
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }

    /// <summary>
    /// Ajax的界面
    /// </summary>
    public class WebUI
    {
        public static BaseUI<ArticleHandler, Content> ArticleUI { get; private set; }
        public static BaseUI<CategoryHandler, CategoryInfo> CategoryUI { get; private set; }
        public static BaseUI<ProductHandler, ProductInfo> ProductUI { get; private set; }
        public static BaseUI<MessageHandler, MessageInfo> MessageUI { get; private set; }
        public static BaseUI<DealerHandler, DealerInfo> DealerUI { get; private set; }
        public static SecurityUI SecurityUI { get; private set; }

        static WebUI()
        {
            ArticleUI = new BaseUI<ArticleHandler, Content>(new ArticleHandler());
            CategoryUI = new BaseUI<CategoryHandler, CategoryInfo>(new CategoryHandler());
            ProductUI = new BaseUI<ProductHandler, ProductInfo>(new ProductHandler());
            MessageUI = new BaseUI<MessageHandler, MessageInfo>(new MessageHandler());
            DealerUI = new BaseUI<DealerHandler, DealerInfo>(new DealerHandler());
            SecurityUI = new SecurityUI();
        }

        /// <summary>
        /// 此方法重UIHelper里拷贝过来的，主要是为了不用传递程序集的信息
        /// </summary>
        /// <param name="uiName"></param>
        /// <param name="uiMethod"></param>
        /// <returns></returns>
        public static string ExecuteNonQuery(string uiName, string uiMethod)
        {
            var arry = uiName.Split(". ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (2 > arry.Length)
                throw new ArgumentException("ui的名字，必须是“命名空间.类名.静态属性名”，例如My.Blog.WebUI.ArticleUI");

            var len = arry.Length - 1;
            var arry1 = new string[len];
            Array.Copy(arry, arry1, len);

            Type t = Type.GetType(string.Join(".",arry1), true, true);
            // 这里有点疑惑，为什么加上BindingFlags.Static就会失败
            object obj = t.InvokeMember(arry[len], BindingFlags.GetProperty | BindingFlags.GetField, null, null, null);
            // 这里有点疑惑，这里为什么可以用obj来调用静态方法
            return (string)(obj.GetType().InvokeMember(uiMethod, BindingFlags.InvokeMethod, null, obj, null));
        }
    }
}
